(function(){
	var idProduct = -1, //this id minus one after creating new product  
	// arrayLoadTimes = new Array(0,0,0), //one way array to record loading data times, format as: (status, level, category)
	idProductDelete, //collect product id to be delete
	sLastCategorty, //set new product category as last new product category
	jsonProduct = new Array(), //collect all the changed product info
	jsonProductDelete = new Array(), //collect delete id
	classIconPlus = "icon-plus",
	classIconMinus = "icon-minus",
	classIconSave = "btn-save",
	classDisplay = "dd-display",
	classImage = "dd-detail",
	classStatus = "dd-status",
	classLevel = "dd-level",
	classCategory= "dd-category",
	bInitialLoad = true; //header combobox or combotree loading

	// initiate product list table
	var oTable = $('#product_list').dataTable({
		//"sDom": "<'row-fluid'<'span6'l><'span6'f>r>t<'row-fluid'<'span6'i><'span6'p>>",
		"sDom": "<'row-fluid'<'span6'l><'span6'>r>t<'row-fluid'<'span6'i><'span6'p>>",
		"sPaginationType": "bootstrap",
		"sInitialType": "product_list",
		"bStateSave": true,
		"aLengthMenu": [[10, 25, 50, -1], [10, 25, 50, "所有"]],
		"oLanguage": {
			"sLengthMenu": "每页 _MENU_ 个产品",
			"oPaginate": {
				"sFirst": "首页",
				"sPrevious": "上页",
				"sNext": "下页",
				"sLast": "末页",
			},
		//	"sSearch": "搜索 ",
			"sInfo": "显示第 _START_ 到 _END_ ，共 _TOTAL_ 个",
			"sEmptyTable": "没有产品，请添加",
			"sInfoEmpty": "0个产品",
			"sZeroRecords": "没有匹配的产品",
		},
		"aoColumnDefs": [
			{'bSortable': false, 'aTargets': [0]},
			{'bSortable': false, 'aTargets': [1]},
			{'bSortable  ': false, 'aTargets': [3]},
			{'bSortable': false, 'aTargets': [4]},
		]
	});
	
//	oTable.fnReloadAjax( 'file:///E:/MobSol/PupilBeast-Web/Admin%20Web/data/pl.txt', jsonProduct);
    oTable.fnReloadAjax( 'file:///E:/MobSol/PupilBeast-Web/Admin%20Web/data/pl.txt', jsonProduct);

	//load combo in the table header and filter data
	var arrayHeader = oTable.fnGetHeaders()[0];
	for (var i=0; i<arrayHeader.length; i++){
		var elHeader = arrayHeader[i];
			
		//load Combo for header
		if ($(elHeader.cell).hasClass(classStatus)){
			var elHandler = $('<input class="' + classStatus + '"></select>');
			elHandler.appendTo($(elHeader.cell));
			
			//product list combobox execution
			elHandler.combobox({
				url:'data/product-status-header.json',//添加全部选项
				valueField:'id',
				textField:'text',
				panelHeight: 'auto',
				editable: false,
				onLoadSuccess: function(param){
					$(this).combobox('setValue', '状态');
				},
				onChange:function(param){
					// var test = $(this).parent()[0];
					// var aPos = oTable.fnGetPosition($(this).parent()[0]);
					if (bInitialLoad == false)
						oTable.fnFilter(param, 2);

					// var val = $.fn.dataTable.util.escapeRegex($(this).children("select").val());

					// column.search( val ? '^'+val+'$' : '', true, false ).draw();

					// column.data().unique().sort().each( function ( d, j ) {
						// select.append( '<option value="'+d+'">'+d+'</option>' )
					// } );
				}
			});
		}
		if ($(elHeader.cell).hasClass(classLevel)){
			var elHandler = $('<input class="' + classLevel + '"></select>');
			elHandler.appendTo($(elHeader.cell));
		
			elHandler.combobox({
				url:'data/product-level-header.json',
				valueField:'id',
				textField:'text',
				panelHeight: 'auto',
				editable: false,
				onLoadSuccess: function(param){				
					$(this).combobox('setValue', '新品');
				},
				onChange:function(param){
					//do sth.
				}
			});
		}
		
		if ($(elHeader.cell).hasClass(classCategory)){
			var elHandler = $('<input class="' + classCategory + '"></select>');
			elHandler.appendTo($(elHeader.cell));

			elHandler.combotree({
				url:'data/product-category-header.json',
				panelHeight: 'auto',
				editable: false,
				onLoadSuccess: function(param){
					elHandler.combotree('setValue', "分类");
				},
				onChange:function(param){
					//do sth.
				}
			});
		}
		
		//onchange  用共同的模块？
		if (i==arrayHeader.length) bInitialLoad = false;
	}
	

	//add a new product
	$(document).on("click", "." + classIconPlus, function(){    
		var nTr = $('<tr class="odd gradeX" data-id="' + idProduct + '">'+
						'<td><input type="checkbox" class="checkboxes" value="1" /></td>'+
						'<td>\
							<img class="dd-detail" src="img/NewProduct.png">\
							<input class="dd-file" id="imgPic' + idProduct + '" type="file" name="uploadImg">\
							<input class="dd-display" maxlength="50" value=" 双击输入产品名字"/>\
						</td>'+
						'<td class="hidden-phone"><input class="dd-status"/></td>'+
						'<td class="hidden-phone"><input class="dd-level"/></td>'+
						'<td class="center hidden-phone"><input class="dd-category"/></td>'+
					'</tr>');
		oTable.fnAddTr( nTr[0]);
		idProduct += -1;

		loadNewCombo(nTr);
		
		// when category name changed, the new name will be save to jsonProduct
		$("." + classDisplay, nTr).watch(function(value, e){
			updateArrayChanged("name", value, e, jsonProduct);
		});
	});
	
	var loadNewCombo = function(nTr){
		var elInput;
		
		//set bInitialLoad as true to load new combo default value
		// bInitialLoad = true;
		// load status combo and set default value
		elInput = $('input.' + classStatus, nTr);
		elInput.combobox({
			url:'data/product-status.json',    
			valueField:'id',
			textField:'text',
			panelHeight: 'auto',
			editable: false,
			onChange:function(param){
				// if (param && bInitialLoad == false){
					var elParent = $(this).parent();
					
					if (elParent[0].nodeName != "TH"){
						updateArrayChanged("status", param, elParent, jsonProduct);
					}
				// }									
			}
		});
		elInput.combobox('select', 2);
		
		// load level combo and set default value
		elInput = $('input.' + classLevel, nTr);
		elInput.combobox({
			url:'data/product-level.json',
			valueField:'id',
			textField:'text',
			panelHeight: 'auto',
			editable: false,
			onChange:function(param){
				// if (param && bInitialLoad == false){
					var elParent = $(this).parent();
					
					if (elParent[0].nodeName != "TH"){
						updateArrayChanged("level", param, elParent, jsonProduct);
					}
				// }
			}
		});
		elInput.combobox('select', 0);
		
		// load category combo and set default value
		elInput = $('input.' + classCategory, nTr);
		elInput.combotree({
		//	url:'data/product-category.json',
            url:'data/product-category.json',
			valueField:'id',
			textField:'text',
			panelHeight: 'auto',
			editable: false,
			onChange:function(param){
				var elParent = $(this).parent();
				
				if (elParent[0].nodeName != "TH"){
					updateArrayChanged("category", param, elParent, jsonProduct);
					sLastCategorty = param;
				}
			}
		});
		if (sLastCategorty != undefined)
			elInput.combotree('setValue', sLastCategorty);
		
		//set bInitialLoad as false after setting new combo default value
		// bInitialLoad = false;
	}

	//delete a product
	$(document).on("click", "." + classIconMinus, function(){
		if ($("input[type='checkbox']:checkbox:checked").length > 0){
			swal({
					title: "真的决定删除吗?",
					text: "将无法恢复要删除的产品！",
					type: "warning",
					showCancelButton: true,
					confirmButtonColor: "#DD6B55",
					confirmButtonText: "决定删除",
					cancelButtonText: "取消",
					closeOnConfirm: false
				}, 
				function(){
					$("input[type='checkbox']:checkbox:checked").each(function(){ 
						// Immediately remove the first producted
						oTable.fnDeleteRow( oTable.fnGetPosition(this.closest("tr")));
						
						updateArrayChanged("delete", "", this, jsonProduct);				

						if (parseInt($(this.closest("tr")).data("id")) > 0) {
							//if products to be delete on server, push to array to send to server
							jsonProductDelete.push($(this.closest("tr")).data("id"));
						}
					});
					
					// if array is not zero length, push array to server to delete products
					if (jsonProductDelete.length > 0){
						var  strJsonProductDelete = JSON.stringify(jsonProductDelete);
						alert(strJsonProductDelete);
						
						function handleAjax(){
							$.ajax({ 
								async: false,
								type : "POST",
							//    dataType : 'Text', 
								contentType : 'application/json',
								url:"/app_admin/handle_product_list_delete/",
								data : strJsonProductDelete,
							
								error:function(result){
									//upload tree ajax failed
									//info user to continue editing or save again
									swal({
											title: "删除失败",
											text: "是否要重新删除呢？如果取消可以继续编辑。",
											type: "warning",
											showCancelButton: true,
											confirmButtonColor: "#DD6B55",
											confirmButtonText: "继续删除",
											cancelButtonText: "取消",
											closeOnConfirm: false 
										},
										function(){
											//swal("继续执行删除", "尝试上一次删除内容", "success"); 
											//deleted already, append ajax to server again
											handleAjax();
									});					
								},
								
								success:function(result){
									swal({   
										title: "删除成功",   
										text: "可以继续编辑了！",
										confirmButtonText: "知道了" 
									});
								}
							});
						}
						handleAjax();
					}
			});
		}else{
			swal("没有选择产品", "请选择要删除的产品", "error"); 
		}
		//reset json of deleting products
		jsonProductDelete =  Array();
	});
	
	//when click a image in product list
	$(document).on('click','.' + classImage, function(e){
		var idCurrentProduct;
		
		//check if there is product info to be save 
		if(jsonProduct.length == 0){
			return;
		}else{
			saveInfo();
		}
		
		idCurrentProduct = $(e.currentTarget.closest("tr")).data("id");
        self.location="/app_admin/product_list_detail/"+idCurrentProduct+"/";
	});
	
	//when click save button, send tree JSON and images to server
	$(document).on("click", "." + classIconSave, function handle(){
		if (jsonProduct.length == 0){
			swal("没有任何改动需要保存","继续修改产品吧！");
		}else
			saveInfo();
	});
		
	function saveInfo(){
		var bReturn = false;
		
		//make sure category of new products is selected
		$('#product_list tbody').find('tr').each(function(){
			if ($(this).data('id') < 0){
				var test = $(this).find('.' + classCategory).combotree("getValue") ;
				if ($(this).find('.' + classCategory).combotree("getValue") == ''){
					bReturn = true;
					return false;
				}
			}
		});
		if (bReturn){
			swal({   
				title: "请选择产品分类",   
				text: "选择产品分类后再保存",
				confirmButtonText: "好的" 
			});
			return true;
		}
		
		$('#product_list tbody').find('tr').each(function(){
			if ($(this).data('id') < 0){
				updateArrayChanged("name", $(this).find('.' + classDisplay).val(), this, jsonProduct);
				// updateArrayChanged("status", $(this).find('.' + classStatus).SelectedValue, this, jsonProduct);
				// updateArrayChanged("level", $(this).find('.' + classLevel).SelectedValue, this, jsonProduct);
			}
		});
		
		var  strJsonProduct;
		
		strJsonProduct = JSON.stringify(jsonProduct);
		alert(strJsonProduct);
		
		$.ajax({ 
			async: false,
			type : "POST",
		//    dataType : 'Text', 
			contentType : 'application/json',
			url:"/app_admin/handle_product_list_update/",
			data : strJsonProduct,
		
			error:function(result){
				//upload tree ajax failed
				//info user to continue editing or save again
				swal({
						title: "上传失败",
						text: "是否要重新上传呢？如果取消可以继续编辑。",
						type: "warning",
						showCancelButton: true,
						confirmButtonColor: "#DD6B55",
						confirmButtonText: "继续上传",
						cancelButtonText: "取消",
						closeOnConfirm: false 
					}, 
					function(){
						swal("继续执行上传", "尝试上一次上传内容", "success"); 
						handle();
				});					
			},
			
			success:function(result){
				var soldId,strJson =result,
					listJson = eval("("+strJson+")");

				for (var i=0; i< listJson.length; i++){
					oTable.find('tbody > tr').each(function(){
						oldId = $(this).data('id');
						if (oldId == listJson[i]['old_id']){
							$(this).data('id',listJson[i]['new_id']);
						}
					});
				}
				//reset jsonProduct after successful upload
				jsonProduct = Array();
				// if user click product image, don't give the successful execution result
				if($(this).hasClass(classIconSave))
					swal({   
						title: "上传成功",   
						text: "可以继续编辑了！",
						confirmButtonText: "知道了" 
					});
			}
		});		
	}

	//checkbox manipulation
	jQuery('#product_list .group-checkable').change(function () {
		var set = jQuery(this).attr("data-set");
		var checked = jQuery(this).is(":checked");
		jQuery(set).each(function () {
			 if (checked) {
				  $(this).attr("checked", true);
			 } else {
				  $(this).attr("checked", false);
			 }
		});
		jQuery.uniform.update(set);
	});

})();